package com.hoperun.udpbroadcast.slice;

import com.hoperun.udpbroadcast.Log;
import com.hoperun.udpbroadcast.ResourceTable;
import com.hoperun.udpbroadcast.broadcast.BroadcastUtils;
import com.hoperun.udpbroadcast.broadcast.Config;
import com.hoperun.udpbroadcast.broadcast.UdpBroadcastClient;
import com.hoperun.udpbroadcast.broadcast.UdpBroadcastServer;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.utils.zson.ZSONObject;

import java.net.DatagramSocket;
import java.net.SocketException;

public class EnviromentAbilitySlice extends AbilitySlice {
    Config config;
    Text tempTx,humiTx,gasTx;
    UdpBroadcastServer server;
    DatagramSocket socket;
    EventHandler updateHandler;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_enviroment);
        config = Config.parseIntent(intent);

        findComponentById(ResourceTable.Id_send_temp_btn).setClickedListener(this::onSendTempBtn);
        findComponentById(ResourceTable.Id_send_humi_btn).setClickedListener(this::onSendHumiBtn);
        findComponentById(ResourceTable.Id_send_gas_btn).setClickedListener(this::onSendGasBtn);

        tempTx = (Text) findComponentById(ResourceTable.Id_watch_temp_tx);
        humiTx = (Text) findComponentById(ResourceTable.Id_watch_humi_tx);
        gasTx = (Text) findComponentById(ResourceTable.Id_watch_gas_tx);

        try {
            socket = new DatagramSocket(config.getBroadcastPort());
        } catch (SocketException e) {
            e.printStackTrace();
            Log.e("creat socket error",e);
        }
        server = new UdpBroadcastServer(config.getBroadcastServerPort());
        server.setCallback(((address, receive) -> {
            final ZSONObject json = ZSONObject.stringToZSON(receive);
            if(json.containsKey("temp") || json.containsKey("humi")|| json.containsKey("gas")) {
                getUITaskDispatcher().asyncDispatch(() -> {
                    tempTx.setText(String.valueOf(json.getFloat("temp")));
                    humiTx.setText(String.valueOf(json.getFloat("humi")));
                    gasTx.setText(String.valueOf(json.getFloat("gas")));
                });
            }
        }));
        server.setSocket(socket);

        findComponentById(ResourceTable.Id_previousBtn).setClickedListener(this::onClickPrevious);
        findComponentById(ResourceTable.Id_updateBtn).setClickedListener(this::onClickUpdate);

        updateHandler = new EventHandler(EventRunner.create());
        updateHandler.postTask(this::autoUpdate, 1000);
    }

    private void autoUpdate(){
        onClickUpdate(null);
        updateHandler.postTask(this::autoUpdate, 60000);
    }

    private void onClickUpdate(Component component) {
        ZSONObject json = new ZSONObject();
        json.put("update", 0);
        UdpBroadcastClient client = new UdpBroadcastClient();
        client.setSocket(socket);
        client.setAddress(config.getBroadcastIp(), config.getBroadcastPort());
        client.send(json.toString());
    }

    private void onSendGasBtn(Component component) {
        TextField gasEdit = (TextField) findComponentById(ResourceTable.Id_gas_max_edit);
        int gas = BroadcastUtils.parseInt(gasEdit);
        gas = Math.max(300,Math.min(gas,10000));

        ZSONObject json = new ZSONObject();
        json.put("gas_value", String.valueOf(gas));
        UdpBroadcastClient client = new UdpBroadcastClient();
        client.setSocket(socket);
        client.setAddress(config.getBroadcastIp(), config.getBroadcastPort());
        client.send(json.toString());
    }

    private void onSendHumiBtn(Component component) {
        TextField minEdit = (TextField) findComponentById(ResourceTable.Id_humi_min_edit);
        TextField maxEdit = (TextField) findComponentById(ResourceTable.Id_humi_max_edit);
        float min = BroadcastUtils.parseFloat(minEdit);
        float max = BroadcastUtils.parseFloat(maxEdit);

        ZSONObject json = new ZSONObject();
        json.put("humi_max", String.valueOf(max));
        json.put("humi_min", String.valueOf(min));
        UdpBroadcastClient client = new UdpBroadcastClient();
        client.setSocket(socket);
        client.setAddress(config.getBroadcastIp(), config.getBroadcastPort());
        client.send(json.toString());
    }

    private void onSendTempBtn(Component component) {
        TextField minEdit = (TextField) findComponentById(ResourceTable.Id_temp_min_edit);
        TextField maxEdit = (TextField) findComponentById(ResourceTable.Id_temp_max_edit);
        float min = BroadcastUtils.parseFloat(minEdit);
        float max = BroadcastUtils.parseFloat(maxEdit);

        ZSONObject json = new ZSONObject();
        json.put("temp_max", String.valueOf(max));
        json.put("temp_min", String.valueOf(min));
        UdpBroadcastClient client = new UdpBroadcastClient();
        client.setSocket(socket);
        client.setAddress(config.getBroadcastIp(), config.getBroadcastPort());
        client.send(json.toString());
    }

    private void onClickPrevious(Component component) {
        terminate();
//        ActivityTools.changePage(this,new LightAbilitySlice(),config.createIntent());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        if (socket != null ) {
//            socket.disconnect();
            socket.close();
            socket = null;
        }
        if(updateHandler != null){
            updateHandler.removeAllEvent();
            updateHandler = null;
        }
        super.onStop();
    }
}
